package com.service.template;

import com.model.AccessToken;
import com.model.template.TemplateData;
import com.model.template.WxTemplate;
import com.thread.AccessTokenThread;
import com.util.WeixinUtil;
import net.sf.json.JSONObject;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;


public class Template {

    private static org.slf4j.Logger log = LoggerFactory.getLogger(Template.class);

    /**
     * 发送测试版的模板消息
     * openId 用户标识
     */
    public static void send_template_message() {
        //固定的openid
        String openId="obcuqxGCSU44QIdKCu-vyPFJ5Ssc";
        AccessToken token = AccessTokenThread.accessToken;
        String access_token = token.getToken();
        String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + access_token;
        WxTemplate temp = new WxTemplate();

        //点击通知后跳转的页面(如果不写，iphone跳转空白页，安卓无法打开)
        temp.setUrl("http://weixin.qq.com/download");

        //设置发送的openid
        temp.setTouser(openId);
        temp.setTopcolor("#000000");
        temp.setTemplate_id("A3ASr7ZRDCvao3TYUMGyxus7mKL2xiFvyhB-9gV3Juw");//测试模块id
        Map<String, TemplateData> m = new HashMap<String, TemplateData>();
        TemplateData first = new TemplateData();
        first.setColor("#000000");
        first.setValue("这里填写您要发送的模板信息");
        /**
         * 集合中属性对应的是模板中XX的内容————...XX.DATA}}...
         */
        m.put("first", first);
        TemplateData name = new TemplateData();
        name.setColor("#000000");
        name.setValue("第一个属性内容");
        m.put("name", name);
        TemplateData wuliu = new TemplateData();
        wuliu.setColor("#000000");
        wuliu.setValue("第二个属性内容");
        m.put("wuliu", wuliu);
        TemplateData orderNo = new TemplateData();
        orderNo.setColor("#000000");
        orderNo.setValue("第三个属性内容");
        m.put("orderNo", orderNo);
        TemplateData receiveAddr = new TemplateData();
        receiveAddr.setColor("#000000");
        receiveAddr.setValue("第四个属性内容");
        m.put("receiveAddr", receiveAddr);
        TemplateData remark = new TemplateData();
        remark.setColor("#000000");
        remark.setValue("***备注说明***");
        m.put("Remark", remark);
        temp.setData(m);
        String jsonString = JSONObject.fromObject(temp).toString();
        JSONObject jsonObject = WeixinUtil.httpRequest(url, "POST", jsonString);
        System.out.println(jsonObject);
        int result = 0;
        if (null != jsonObject) {
            if (0 != jsonObject.getInt("errcode")) {
                result = jsonObject.getInt("errcode");
                log.error("错误 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
            }
        }
        log.info("模板消息发送结果：" + result);
    }


    /**
     * 发送数据库的模板消息
     * openId 用户标识
     * 目前测试号无法使用非测试版模板id，所以无法实现功能，先不写。
     */
    public static void sendTemplateMessage() {
}
}